<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\File;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class UploadImage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $user;
    public $fileId;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user, $fileId)
    {
        $this->user = $user;
        $this->fileId = $fileId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //获取路径，文件名
        $path = storage_path(). '/uploads/'. $this->fileId;
        $fileName = $this->fileId. '.png';
        //上传到七牛
        if (Storage::disk('qiniu')->put('profile/'. $fileName, fopen($path, 'r+'))) {
            File::delete($path);
        }
        //更改当前用户头像
        $this->user->avtar = $fileName;
        $this->user->save();
    }
}
